package com.jt.utils;

import com.mysql.cj.util.StringUtils;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
public class HttpPostAndGetUtil {
    /**
     * 统一调用http接口封装 get请求
     *
     * @param pathUrl
     */
    public String doGet(String pathUrl, Map<String, Object> mapData, String type) {
        OutputStreamWriter out = null;
        BufferedReader br = null;
        String result = "";
        try {
            //GET请求直接在链接后面拼上请求参数
            String mPath = pathUrl + "?";
            for (String key : mapData.keySet()) {
                mPath += key + "=" + mapData.get(key) + "&";
            }

            URL url = new URL(mPath);
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //请求方式
            conn.setRequestMethod(type);
            //conn.setRequestMethod("GET");

            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");

            /**
             * 下面的三句代码，就是调用第三方http接口
             */
            //获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            //发送请求参数即数据
//            out.write(data);
            //flush输出流的缓冲
            out.flush();

            /**
             * 下面的代码相当于，获取调用第三方http接口后返回的结果
             */
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null) {
                result += str;
            }
            System.out.println(result);
            //关闭流
            is.close();
            //断开连接，disconnect是在底层tcp socket链接空闲时才切断，如果正在被其他线程使用就不切断。
            conn.disconnect();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    /**
     * 统一调用http接口封装 post请求 json 格式
     *
     * @param pathUrl
     */
    public String postJson(String pathUrl, String json, String type, String token) {
        HttpURLConnection httpURLConnection = null;
        String result = null;
        try {
            URL urls = new URL(pathUrl);
            httpURLConnection = (HttpURLConnection) urls.openConnection();
            httpURLConnection.setRequestMethod(type);
            //Content-type字母区分大小写，特别注意
//            httpURLConnection.setRequestProperty("Content-type", "application/json");
            httpURLConnection.setRequestProperty("accept", "*/*");
            httpURLConnection.setRequestProperty("connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            if (StringUtils.isNullOrEmpty(token)) {
                httpURLConnection.setRequestProperty("token", token);
            }
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.setConnectTimeout(30000);
            httpURLConnection.connect();
            //获取输出流对象，把请求参数发送打服务器接口
            OutputStream outputStream = httpURLConnection.getOutputStream();
            outputStream.write(json.getBytes("utf-8"));
            outputStream.flush();
            //获取服务器返回数据流
            InputStream inputStream = null;
            if (sun.net.www.protocol.http.HttpURLConnection.HTTP_OK == httpURLConnection.getResponseCode()) {
                inputStream = httpURLConnection.getInputStream();
            } else {
                inputStream = httpURLConnection.getErrorStream();
            }
            // 内存流对象
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] data = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(data)) != -1) {
                byteArrayOutputStream.write(data, 0, len);
            }
            result = new String(byteArrayOutputStream.toByteArray(), "utf-8");

            inputStream.close();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;


    }


    public String postFormData(String url, Map<String, Object> map, String FileType, String token) throws Exception {
        System.out.println(FileType);
        BufferedReader in = null;
        URL urls = new URL(url);
        HttpURLConnection connection = null;
        OutputStream outputStream = null;
        String rs = "";
        try {
            connection = (HttpURLConnection) urls.openConnection();
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----footfoodapplicationrequestnetwork");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
            connection.setRequestProperty("Accept", "*/*");
            connection.setRequestProperty("Range", "bytes=" + "");
            if (StringUtils.isNullOrEmpty(token)) {
                connection.setRequestProperty("token", token);
            }
            connection.setConnectTimeout(8000);
            connection.setReadTimeout(20000);
            connection.setRequestMethod("POST");
            StringBuffer buffer = new StringBuffer();
            outputStream = connection.getOutputStream();
            Set<Map.Entry<String, Object>> entries = map.entrySet();
            for (Map.Entry<String, Object> entry : entries) {
                // 每次都清空buffer，避免写入上次的数据
                buffer.delete(0, buffer.length());
                buffer.append("------footfoodapplicationrequestnetwork\r\n");
                Object value = entry.getValue();
                if (!(value instanceof File)) {
                    buffer.append("Content-Disposition: form-data; name=\"");
                    buffer.append(entry.getKey());
                    buffer.append("\"\r\n\r\n");
                    buffer.append(entry.getValue());
                    buffer.append("\r\n");
                    outputStream.write(buffer.toString().getBytes());
//                  System.out.println(buffer.toString());
                } else {
                    buffer.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"; filename=\"" + ((File) entry.getValue()).getName() + "\"\r\n");
                    buffer.append("Content-Type: " + FileType + "\r\n\r\n");
//                    System.out.println(buffer.toString());
                    outputStream.write(buffer.toString().getBytes());
                    File file = (File) entry.getValue();
                    DataInputStream ins = new DataInputStream(new FileInputStream(file));
                    int bytes = 0;
                    byte[] bufferOut = new byte[1024];
                    while ((bytes = ins.read(bufferOut)) != -1) {
                        outputStream.write(bufferOut, 0, bytes);
//                        System.out.print("A");
                    }
                    // 文件流后面添加换行，否则文件后面的一个参数会丢失
                    outputStream.write("\r\n".getBytes());
//                    System.out.println("\r\n");
                }
            }
            if (entries != null && map.size() > 0) {
                buffer.delete(0, buffer.length());
                buffer.append("------footfoodapplicationrequestnetwork--\r\n");
//                System.out.println(buffer.toString());
            }
            outputStream.write(buffer.toString().getBytes());
            try {
                connection.connect();
                if (connection.getResponseCode() == 200) {
                    in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                    String line = "";
                    while ((line = in.readLine()) != null) {
                        rs += line;
                    }
                }
            } catch (Exception e) {
                System.out.println("发生异常");
                rs = null;
            }
            return rs;
        } finally {
            try {
                outputStream.close();
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
            }
            outputStream = null;
            if (connection != null)
                connection.disconnect();
            connection = null;
        }
    }


    public static void main(String[] args) {
        String url = "http://localhost:???";
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("lineSta", "0121");
        map.put("devTypeId", "04");
        map.put("deviceId", "034");
        map.put("inOutType", "10");
        map.put("versionNo", "1016");
        map.put("deviceTime", String.valueOf(System.currentTimeMillis()));
        String PATH = "C:\\Users\\THUN\\Desktop\\智慧小区文档\\hongheng.zip";
        File file = new File(PATH); // 文件路径，基于项目，在项目根目录建立file文件夹，01.zip
        map.put("logFileName", file.getName()); // 上传文件名，与文件保持一致，这里自动获取
        map.put("uploadFile", file); // 上传的文件
        String returnStr2 = "";
        try {
            File uploadFile = (File) map.get("uploadFile");
            int i = uploadFile.getName().lastIndexOf(".");
            String substring = uploadFile.getName().substring(i + 1, uploadFile.getName().length());
//            returnStr2 =postFormData(url, map,null);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        System.out.println(returnStr2);
    }


}
